<?php
/**
 * 地产控制器包含（楼盘，二手房， 租房）
 */
namespace app\index\controller;

use app\common\exception\System as SystemException;
use Exception;
use think\Db;
use \think\Request;
use Log;
use app\common\library\Payment;
class Landed extends Common
{
    /**
     * 不需要登录
     * @var array
     */
    protected $noNeedLogin = ['index','getMainIndex','getInfo','getResource','getShop','getShopCategory','getSearch','reserve','getMyCarList','getAround','getWxPayNotify','getCommentInfo','getCommentList','getAliPayNotify'];
//   protected $noNeedLogin = ['index','getMainIndex','getInfo','getResource','getShop','getShopCategory','getSearch','reserve','getMyCarList','getAround','getWxPayNotify'];



    /**
     * 地产主页
     */
    public function index()
    {
        $city = trim($this->request->post('city'));
        $res = service('index/Landed')->index($city);
        return $this->successReturn($res,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     * @return \think\Response
     * 获取楼盘/二手房/租房首页
     */
    public function getMainIndex()
    {
        $type = intval(trim($this->request->post('type')));
        $city = trim($this->request->post('city'));
        $page = trim($this->request->post('page'));
        $page_size = trim($this->request->post('page_size'));
        $area = trim($this->request->post('area'));
        $metro = trim($this->request->post('metro'));
        $distance = trim($this->request->post('distance'));
        $latlng = trim($this->request->post('latlng'));
        $cate = trim($this->request->post('category'));
        $cate_info = trim($this->request->post('cate'));
        $price = trim($this->request->post('price'));
        $room = trim($this->request->post('room'));
        $room_size = trim($this->request->post('room_size'));
        $param['area'] = $area;
        $param['metro'] = $metro;
        $param['distance'] = $distance;
        $param['latlng'] = $latlng;
        $res = service('index/Landed')->getMainIndex($type,$city,$page,$page_size,$param,$cate,$price,$room,$room_size,$cate_info);
        return $this->successReturn($res,SystemException::E_SUCCESS, '获取成功');
    }

    /**
     * @return \think\Response
     * 获取详情
     */
    public function getInfo()
    {
        $member_id = $this->auth->member_id;
        $type = intval(trim($this->request->post('type')));
        $id = intval(trim($this->request->post('id')));
        $res = service('index/Landed')->getInfo($type,$id,$member_id);
        return $this->successReturn($res,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     * @return \think\Response
     * 获取楼盘/二手房/租房资源
     */
    public function getResource()
    {
        $type = intval(trim($this->request->post('type')));
        $id = intval(trim($this->request->post('id')));
        $resource = intval(trim($this->request->post('resource')));
        $res = service('index/Landed')->getResource($type,$id,$resource);
        return $this->successReturn($res,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     * @return \think\Response
     * 获取店铺主页
     */
    public function getShop()
    {
        $id = intval(trim($this->request->post('id')));
        $keyword = trim($this->request->post('keyword'));
        $page = trim($this->request->post('page'));
        $page_size = trim($this->request->post('page_size'));
        $res = service('index/Landed')->getShop($id,$keyword,$page,$page_size);
        return $this->successReturn($res,SystemException::E_SUCCESS, '获取成功');
    }

    /**
     * @return \think\Response
     * 获取店铺分类
     */
    public function getShopCategory()
    {
        $id = intval(trim($this->request->post('id')));
        $cid = intval(trim($this->request->post('cid')));
        $page = trim($this->request->post('page'));
        $page_size = trim($this->request->post('page_size'));
        $res = service('index/Landed')->getShopCategory($id,$cid,$page,$page_size);
        return $this->successReturn($res,SystemException::E_SUCCESS, '获取成功');
    }

    /**
     * @return \think\Response
     * 获取区域/地铁信息
     */
    public function getSearch()
    {
        $search_type = intval(trim($this->request->post('search_type')));
        $city = trim($this->request->post('city'));
        if($search_type == 1){
            $list = service('index/Landed')->getArea($city);
        }else{
            $list = service('index/Landed')->getMetroStation($city);
        }
        return $this->successReturn($list,SystemException::E_SUCCESS, '获取成功');
    }

    /**
     * 获取周边信息
     */
    public function getAround()
    {
        $keyword = trim($this->request->post('keyword'));
        $latlng = trim($this->request->post('latlng'));
        $list = service('index/Landed')->getAround($keyword,$latlng);
        return $this->successReturn($list,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     *添加购物车
     */
    public function addMyCar()
    {

        $goods_id = intval(trim($this->request->post('goods_id')));
//        $member_id = intval(trim($this->request->post('member_id')));
        $member_id = $this->auth->member_id;

        $type = intval(trim($this->request->post('type')));
        if(empty($goods_id) || empty($member_id) || empty($type)){
            return $this->errorReturn(SystemException::E_VALIDATE,'确实必要参数');
        }
        $ret = service('index/Landed')->addMyCar($goods_id,$member_id,$type);
        if(!$ret){
            return $this->errorReturn(SystemException::E_VALIDATE,'添加失败');
        }else{
            return $this->successReturn($ret,SystemException::E_SUCCESS, '添加成功');
        }
    }


    /**
     * @return \think\Response
     * 删除购物车
     */
    public function delMyCar()
    {
        $goods_id = intval(trim($this->request->post('goods_id')));
//        $member_id = intval(trim($this->request->post('member_id')));
        $member_id = $this->auth->member_id;

        $type = intval(trim($this->request->post('type')));
        if(empty($goods_id) || empty($member_id) || empty($type)){
            return $this->errorReturn(SystemException::E_VALIDATE,'确实必要参数');
        }
        $ret = service('index/Landed')->delMyCar($goods_id,$member_id,$type);
        if(!$ret){
            return $this->errorReturn(SystemException::E_VALIDATE,'删除失败');
        }else{
            return $this->successReturn($ret,SystemException::E_SUCCESS, '删除成功');
        }
    }

    /**
     * @return \think\Response
     * 获取我的购物车
     */
    public function getMyCarList()
    {
//        $member_id = intval(trim($this->request->post('member_id')));
        $member_id = $this->auth->member_id;

        $ret = service('index/Landed')->getMyCarList($member_id);
        return $this->successReturn($ret,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     * @return \think\Response
     * 获取在线预定详情
     */
    public function reserve()
    {
//        $member_id = intval(trim($this->request->post('member_id')));
        $member_id = $this->auth->member_id;

        $type = intval(trim($this->request->post('type')));
        $id = intval(trim($this->request->post('id')));
        $room_id = intval(trim($this->request->post('room_id')));
        $ret = service('index/Landed')->getReserve($member_id,$type,$id,$room_id);
        return $this->successReturn($ret,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     * @return \think\Response
     * 预创建订单
     */
    public function createOrder()
    {
        $goods_id = intval(trim($this->request->post('goods_id')));
        $member_id = $this->auth->member_id;
//        $member_id = intval(trim($this->request->post('member_id')));
        $type = trim($this->request->post('type'));
        $fromcar = intval(trim($this->request->post('fromcar')));
//        $paytype = intval(trim($this->request->post('paytype')));
        $floor_id = intval(trim($this->request->post('floor_id')));
        $ret = service('index/Landed')->createOrder($goods_id,$member_id,$type,$floor_id,$fromcar);
        return $this->successReturn($ret,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     * @return \think\Response
     * 提交订单
     */
    public function submitOrder()
    {
        $ip = $this->request->ip();
        $goods_id = trim($this->request->post('goods_id'));
        $member_id = $this->auth->member_id;
        $buy_type = trim($this->request->post('buy_type'));
//        $member_id = intval(trim($this->request->post('member_id')));
        $type = trim($this->request->post('type'));
        $paytype = intval(trim($this->request->post('paytype')));
        $floor_id = intval(trim($this->request->post('floor_id')));
        $stages = intval(trim($this->request->post('stages')));
        $fromcar = intval(trim($this->request->post('fromcar')));
        $ret = service('index/Landed')->submitOrder($goods_id,$member_id,$type,$paytype,$buy_type,$stages,$floor_id,$ip,$fromcar);
        if($ret['status'] == 1){
            return $this->successReturn($ret,SystemException::E_SUCCESS, '提交订单成功');
        }else{
            return $this->errorReturn(SystemException::E_VALIDATE,$ret['msg']);
        }
    }

    /**
     * @return bool
     * 房产支付回调
     */
    public function getWxPayNotify()
    {
//        $xmlData = $this->request->getContent();
        $xmlData = file_get_contents('php://input');

        //XML格式转换
        $xmlObj = simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA);

        $xmlObj = json_decode(json_encode($xmlObj),true);

        //记录回调日志
        Log::write(serialize($xmlObj),'notice');

        $out_trade_no = $xmlObj['out_trade_no'];

        $type = $xmlObj['attach'];

        $message = $xmlObj;

        $order = service('index/Landed')->getOneOrder($out_trade_no,$type);

        if (!$order || $order['status']==2) { // 如果订单不存在 或者 订单已经支付过了

            $this->response()->write("<xml>
                <return_code><![CDATA[SUCCESS]]></return_code>
                <return_msg><![CDATA[OK]]></return_msg>
                </xml>");
            return false; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        // var_dump($message);
        if ($message['return_code'] === 'SUCCESS')
        {
            // 用户是否支付成功
            if ($message['result_code'] === 'SUCCESS') {
                $orderdata['pay_time'] = time(); // 更新支付时间为当前时间
                $orderdata['update_time'] = time(); // 更新支付时间为当前时间
                $orderdata['status'] = 2;
                $ret = service('index/Landed')->getWxPayNotify($orderdata,$type,$order['id']);

                $this->response()->write("<xml>
                            <return_code><![CDATA[SUCCESS]]></return_code>
                            <return_msg><![CDATA[OK]]></return_msg>
                            </xml>");
                return true;

                // 用户支付失败
            }elseif($message['result_code'] === 'FAIL') {
                echo "fail";
                return false;
            }
        } else {
            echo "fail";
            return false;
        }
        return true; // 返回处理完成
    }


    public function getAliPayNotify()
    {
        $post = $_POST;

        $out_trade_no = $post['out_trade_no'];

        $type = $post['body'];

        Log::write(serialize($post),'notice');

        $order = service('index/Landed')->getOneOrder($out_trade_no,$type);

        if (!$order || $order['status']==2) { // 如果订单不存在 或者 订单已经支付过了
            echo "fail";
            return false;
        }
        if(!empty($post)){

            $path = Env::get('root_path') . 'public/sdk/alipay';
            require_once($path . '/aop/AopClient.php');
            require_once($path . '/aop/request/AlipayTradePrecreateRequest.php');
            require_once($path . '/aop/SignData.php');

            $aop = new \AopClient();
            $aop->alipayrsaPublicKey = Payment::$alipay['alipayrsaPublicKey'];
            $signVerified = $aop->rsaCheckV1($post,null,"RSA2");
            if($signVerified){
                if($post['trade_status'] == 'TRADE_SUCCESS' || $post['trade_status'] == 'TRADE_FINISHED'){
                    $orderdata['pay_time'] = time(); // 更新支付时间为当前时间
                    $orderdata['update_time'] = time(); // 更新支付时间为当前时间
                    $orderdata['status'] = 2;
                    $ret = service('index/Landed')->getWxPayNotify($orderdata,$type,$order['id']);
                    echo "success";
                    return true;
                }
            }else{
                echo "fail";
                return false;
            }

        }
    }




    /**
     * 申请店铺
     */
    public function applyShop()
    {
        $member_id = $this->auth->member_id;
        $applyShop = service('index/Landed')->getApplyShop($member_id);
        if($this->request->isPost()){
            $param['name'] = trim($this->request->post('name'));
            $param['phone'] = trim($this->request->post('phone'));
            $param['address'] = trim($this->request->post('address'));
            $param['business_license'] = trim($this->request->post('business_license'));
            $param['license_operation'] = trim($this->request->post('license_operation'));
            $param['is_vefiy'] = 0;
            $ret = service('index/Landed')->setApplyShop($member_id,$param);
            return $this->successReturn($ret,SystemException::E_SUCCESS, '获取成功');
        }
        return $this->successReturn($applyShop,SystemException::E_SUCCESS, '获取成功');
    }


    /**
     * @return mixed
     * 添加评论
     */
    public function addComment()
    {
        $member_id = $this->auth->member_id;
        $param['member_id'] = $member_id;
        $param['type'] = intval(trim($this->request->post('type')));
        $param['pid'] = intval(trim($this->request->post('pid'))) ?? 0;
        $param['store_id'] = intval(trim($this->request->post('store_id')));
        $param['goods_id'] = intval(trim($this->request->post('goods_id')));
        $param['content'] = trim($this->request->post('content'));
        $param['create_time'] = time();
        $ret = service('index/Landed')->addComment($member_id,$param);
        if($ret){
            return $this->successReturn($ret,SystemException::E_SUCCESS, '评论成功');
        }else{
            return $this->errorReturn(SystemException::E_VALIDATE,'评论失败');
        }
    }

    /**
     * @return mixed
     * 点赞
     */
    public function addStart()
    {
        $member_id = $this->auth->member_id;
        $comment_id = intval(trim($this->request->post('comment_id')));
        $is_start = intval(trim($this->request->post('is_start')));
        $ret = service('index/Landed')->addStart($member_id,$comment_id,$is_start);
        if($is_start){
            return $this->successReturn($ret,SystemException::E_SUCCESS, '点赞成功');
        }else{
            return $this->errorReturn(SystemException::E_VALIDATE,'取消点赞');
        }
    }



    /**
     * @return mixed
     * 获取评论详情
     */
    public function getCommentInfo()
    {
        $member_id = $this->auth->member_id;
        $comment_id = intval(trim($this->request->post('comment_id')));
        $res = service('index/Landed')->getCommentInfo($comment_id,$member_id);
        return $this->successReturn($res,SystemException::E_SUCCESS, '评论成功');
    }


    /**
     * @param $type
     * @param $goods_id
     * 获取评论列表
     */
    public function getCommentList()
    {
        $member_id = $this->auth->member_id;
        $goods_id = intval(trim($this->request->post('goods_id')));
        $type = intval(trim($this->request->post('type')));
        $limit = intval(trim($this->request->post('limit')));
        $list = service('index/Landed')->getCommentList($type,$goods_id,$limit,$member_id);
        return $this->successReturn($list,SystemException::E_SUCCESS, '评论成功');
    }


    /**
     * @return mixed
     * 添加收藏
     */
    public function addCollection()
    {
        $member_id = $this->auth->member_id;
        $param['member_id'] = $member_id;
        $param['type'] = intval(trim($this->request->post('type')));
        $param['goods_id'] = intval(trim($this->request->post('goods_id')));
        $param['is_deleted'] = trim($this->request->post('is_deleted'));
        $param['create_time'] = time();
        $res = service('index/Landed')->addCollection($param);
        if($param['is_deleted'] == 0){
            return $this->successReturn($res,SystemException::E_SUCCESS, '收藏成功');
        }else{
            return $this->errorReturn(SystemException::E_VALIDATE,'取消收藏');
        }
    }

    /**
     * @return mixed
     * 批量删除收藏
     */
    public function delCollection()
    {
        $member_id = $this->auth->member_id;
        $ids = trim($this->request->post('ids'));
        $res = service('index/Landed')->delCollection($ids,$member_id);
        return $this->successReturn($res,SystemException::E_SUCCESS, '取消收藏成功');
    }


    /**
     * @return mixed
     * 获取收藏列表
     */
    public function getCollectionList()
    {
        $member_id = $this->auth->member_id;
        $res = service('index/Landed')->getCollectionList($member_id);
        return $this->successReturn($res,SystemException::E_SUCCESS, '收藏成功');
    }

}